import {login,editor,getUserInfo} from "@/api/user"

const state = {
    pass:"admin123",
    username:"",
    nickname:"",
    user_id:"",
    type:1,
    phone:"",
    img:""
}

const mutations = {
    SET_USERNAME(state,payload){
        state.username = payload
    },
    SET_NICKNAME(state,payload){
        state.nickname = payload
    },
    SET_USER_ID(state,payload){
        state.user_id = payload
    },
    DEL_USER_ID(state){
        state.user_id =""
    },
    SET_TYPE(state,payload){
        state.type=payload
    },
    SET_PHONE(state,payload){
        state.phone = payload
    },
    SET_IMAGE(state,payload){
        state.img = payload
    }
}


const actions = {
    // 传递过来的用户名和密码  
    // userInfo
    async login({commit},userInfo){

        let res = await login(userInfo);
        
        // console.log(res,"res")
        if(res.data.length){
            //设置用户名
            commit("SET_USERNAME",res.data[0].username)
            //设置昵称
            commit("SET_NICKNAME",res.data[0].nickname)
            // 设置用户id
            commit("SET_USER_ID",res.data[0].id)
            // 设置权限type
            commit("SET_TYPE",res.data[0].type)
           
            //登陆成功
            return {
                code:200,
                msg:"登陆成功",
                data:res.data[0]
            }
        }else{
            return {
                code:201,
                msg:"用户名或者密码错误",
                data:{}
            }
        }
    },

    async editor({commit},userInfo){
        let {id,phone,img,password} = userInfo
        try{
            let res =  await editor(id,{phone,img,password})   
            commit("SET_PHONE",res.data.phone)
            commit("SET_IMAGE",res.data.img)
            return res

        }catch(err){

        }
    },

    async getUserInfo({commit},id){
      
        try{
            let res =  await getUserInfo(id)   
            commit("SET_PHONE",res.data.phone)
            commit("SET_IMAGE",res.data.img)
            return res

        }catch(err){

        }
    },
 
}


export default {
    state,
    mutations,
    actions
}